import random
import string
from datetime import datetime, timedelta
from flask import current_app, render_template
from .extensions import mail
from .models import EmailCaptcha, db

def generate_captcha(length=6):
    """生成指定长度的数字验证码"""
    return ''.join(random.choices(string.digits, k=length))

def send_verification_email(email, username):
    """发送验证码邮件"""
    # 生成验证码
    captcha = generate_captcha()
    
    # 保存验证码到数据库
    captcha_record = EmailCaptcha(
        email=email,
        captcha=captcha,
        created_at=datetime.utcnow()
    )
    db.session.add(captcha_record)
    db.session.commit()
    
    # 发送邮件
    mail.send_message(
        subject=current_app.config['VERIFICATION_MAIL_SUBJECT'],
        recipients=[email],
        html=render_template('email/verify_email_zyy.html',
                           username=username,
                           captcha=captcha)
    )

def verify_captcha(email, captcha):
    """验证验证码"""
    # 查找最新的验证码记录
    captcha_record = EmailCaptcha.query.filter_by(
        email=email
    ).order_by(EmailCaptcha.created_at.desc()).first()
    
    if not captcha_record:
        return False
    
    # 检查验证码是否过期
    if datetime.utcnow() - captcha_record.created_at > current_app.config['CAPTCHA_EXPIRATION']:
        return False
    
    # 检查验证码是否匹配
    if captcha_record.captcha != captcha:
        return False
    
    # 验证成功后删除验证码记录
    db.session.delete(captcha_record)
    db.session.commit()
    
    return True

def allowed_file(filename):
    """检查文件类型是否允许上传"""
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in current_app.config['ALLOWED_EXTENSIONS'] 